package models

import (
	"errors"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"os"
	"strconv"
	"time"
)

type Blog struct {
	ID          uint   `gorm:"primary_key"`
	Title       string `gorm:"not null;size:256"`
	Content     string `gorm:"type:text;not null"`
	ShowContent string `gorm:"not null"`
	CreatedAt   time.Time
	LookNum     int `gorm:"default:1"`
	BlogType    BlogType
	BlogTypeID  int
	ShowImage   string `gorm:"default:'https://api.ixiaowai.cn/gqapi/gqapi.php'"`
}

type BlogType struct {
	ID   uint `gorm:"primary_key"`
	Name string
}

var DB *gorm.DB

func ConnectMysql() *gorm.DB {
	db, err := gorm.Open("mysql", "root:python12@(127.0.0.1:3306)/gin_blog?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		println("mysql连接错误", err)
		os.Exit(8520)
	}
	DB = db
	return db
}

type BlogPage struct {
	Prev int
	Next int
	Page int
}

func (Blog) Aaa(typename, page_num string) (*[]Blog, *BlogPage, error) {
	blog := new([]Blog)
	pagenum, err := strconv.Atoi(page_num)
	if err != nil {
		pagenum = 1
	}
	blogpage := BlogPage{}
	blogpage.Page = pagenum
	if typename == "all" {
		//DB.Preload("Orders").Find(&blog)
		//log.Println(len(*blog))
		DB.Select([]string{"id", "title", "show_content", "look_num", "created_at", "show_image"}).Offset(((pagenum - 1) * 10)).Limit(11).Order("created_at desc").Find(&blog)

	} else {
		blogtype := BlogType{}
		DB.Where("name = ?", typename).First(&blogtype)
		if blogtype.ID == 0 {
			blogtype.ID = 1
		}
		DB.Where("blog_type_id = ?", blogtype.ID).Select([]string{"id", "title", "show_content", "look_num", "created_at", "show_image"}).Order("created_at desc").Offset((pagenum - 1) * 10).Limit(11).Find(&blog)
	}
	blogpage.Prev = pagenum - 1
	if len(*blog) > 10 {
		blogpage.Next = pagenum + 1
	}
	log.Println(len(*blog))
	if len(*blog) <= 0 {
		return blog, &blogpage, errors.New("找不到数据")
	}
	return blog, &blogpage, nil
}

func (Blog) GetBlog(artid string) (blogs, perns, nexts *Blog) {
	blog, pern, next := Blog{}, Blog{}, Blog{}
	ids, _ := strconv.Atoi(artid)
	DB.Where("id = ?", ids).First(&blog)
	blog.LookNum += 1
	if blog.ID != 0 {
		DB.Model(&blog).Update("look_num", blog.LookNum)
		DB.Where("id > ?", ids).First(&next)
		DB.Where("id < ?", ids).Order("id desc").First(&pern)

	}

	return &blog, &pern, &next
}

//func main() {
//	db := ConnectMysql()
//	defer db.Close()
//	db.AutoMigrate(&BlogType{})
//	db.AutoMigrate( &Blog{})
//}
